<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/04/28
 */
namespace common\logic;

use common\models\Contact as ContactModel;
use common\models\ContactForm;
use yii\validators\DateValidator;

class Contact {
    public static function getContactList($uid,$id = null) {
        if($id)
            $r=ContactModel::getList("owner_uid=$uid AND id=$id");
        else
            $r = ContactModel::getList("owner_uid=$uid");
        foreach ($r as $k => $v) {
            $v['birthday'] === '1000-01-01' && $r[$k]['birthday'] = '';
        }
        return $r;
    }

    public static function deleteContact($uid, $ids = []) {
        $ids = implode(',', $ids);
        ContactModel::delete("id in ($ids) AND owner_uid=$uid");
    }

    public static function saveContacts($uid, $contacts) {
        foreach ($contacts as $contact) {
            $model = new ContactForm();
            $model->load($contact, '');
            $model->validate();
            if ($model->hasErrors()) {
                return [
                    'err' => 1,
                    'msg' => current($model->getFirstErrors())
                ];
            }
            $now = time();
            $data = array_filter($model->getAttributes());
            $data['utime'] = $now;
            if (empty($data['id'])) {//add
                $data['ctime'] = $now;
                $data['owner_uid'] = $uid;
                ContactModel::insert($data);
            } else {
                ContactModel::update($data, "id={$data['id']} AND owner_uid=$uid");
            }
        }
        return ['err' => 0];
    }

    public static function checkContacts($contacts) {
        foreach ($contacts as $contact) {
            $model = new ContactForm();
            $model->load($contact, '');
            $model->validate();
            if ($model->hasErrors()) {
                return [
                    'err' => 1,
                    'msg' => current($model->getFirstErrors())
                ];
            }
        }
        return ['err' => 0];
    }
}
